const mysql = require('mysql2/promise'),
      log   = console.log,
      Koa   = require('koa'),
      app   = new Koa(),
      Router = require('koa-router'),
      router = new Router(),
      fs    = require('fs'),
      path  = require('path'),
      cors  = require('koa2-cors'),
      http  = require('http'),
      https = require('https'),
      body = require('koa-bodyparser'),
      hq = require('./shop_sc.js'),
      hq1 = require('./shoppage.js')
      gohttp = require('gohttp'),
      request = require('request'),
      check = require('./img_check.js');
      up = require('./uploadConfig.js')
const express = require('express');

const options = {
    key:fs.readFileSync(path.join(__dirname,'./fourgoldhua.cn.key')),
    cert:fs.readFileSync(path.join(__dirname,'./fourgoldhua.cn.crt'))
}
app.use(body());
app.use(cors({
    origin: function (ctx) {
        if (ctx.url === '/test') {
          return "*"; // 允许来自所有域名请求
        }
        return 'http://localhost:8080'; // 这样就能只允许 http://localhost:8080 这个域名的请求了 
    },
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
    maxAge: 5,
    credentials: true,
    allowMethods: ['GET', 'POST', 'DELETE'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}))
//顺序
function sortx(a,b){
  return b.date-a.date;
}
//反序
function sortj(a,b){
  return Date.parse(a.date)-Date.parse(b.date);
}
//id筛选
function food(data,id){
    for(var i = 0;i < data.length;i++){
       if(data[i].food!=id){
           data.splice(i,1);
              i-=1;
       }
    }
    return data;
}
//删空
function climg (obj, fn) {
  for (var i in obj) {
      if (typeof obj[i] === 'object') {
            climg(obj[i], fn)
      }
      if (fn(obj[i])) {
          delete obj[i]
      }
  }
}
 
function delimg (foo) {
    if (typeof foo === 'object') {
        for (var i in foo) {
             return false
        }
        return true
    } else {
        return foo === '' || foo === null || foo === undefined
    }
}
//调用 climg(imgs,delximg) 

function time(date){
    t1=date;
    t2=new Date().getTime();
    t = t2 -t1;
    //console.log(t);
    if(t<60*1000) return '刚刚';
    else if(t<3600*1000){ 
        t=(t-t%60000)/60000;
        return t+'分钟前';
    }
    else if(t<24*3600*1000){
        t=(t-t%3600000)/3600000;
        return t+'小时前';
    }
    else if(t<365*24*3600*1000){
        t=(t-t%86400000)/86400000;
        return t+'天前';
    }
    else if(t>365*24*3600*1000){
        t=(t-t%31536000000)/31536000000;
        return t+'年前';
    }
}
//注册商家账号
router.get('/shop_sc/zhuce',async (ctx)=>{
  let {shop_username,shop_password} = ctx.request.query;
  let open_id = ctx.request.header.token;
  let arr = await hq.get_openid(open_id);
  let brr = await hq.get_zhuce(open_id,shop_username,shop_password);
  if(arr.length == 0){
    hq.insertzh(open_id,shop_username,shop_password);
    arr = '账号注册成功'
  }else if(brr.length == 1){
    arr = '登入成功'
  }else if(brr.length == 0){
    arr = '账号密码出错'
  }
  console.log(arr);
  ctx.body = JSON.stringify(arr);
})
//商家入驻-修改img
router.post('/shop_sc/ruzhu',async (ctx)=>{
  let {shop_username,shop_password,shop_name,shop_addr,shop_jwd,shop_tel,shop_time,img1,img2,img3,img4,img5,img6 } = ctx.request.body.formData;
  let open_id = ctx.request.header.token;
  let arr = await hq.get_zhuce(open_id,shop_username,shop_password);
  hq.updateshop(arr[0].id, shop_name, shop_addr, shop_jwd, shop_tel, shop_time, 0, 0, img1, img2, img3, img4, img5, img6, 0)
  await hq1.insert_img(open_id,0,img1);
  await hq1.insert_img(open_id,0,img2);
  await hq1.insert_img(open_id,0,img3);
  let brr = await hq.get_zhuce(open_id,shop_username,shop_password);
  log(brr);
  ctx.body = JSON.stringify(brr);
})
//审核状态
router.get('/shop_sc/shenhe',async (ctx)=>{
  let {shop_username,shop_password} = ctx.request.query;
  let open_id = ctx.request.header.token;
  let arr = await hq.get_zhuce(open_id,shop_username,shop_password);
  log(arr[0].state)
  ctx.body = JSON.stringify(arr[0].state);
})

//登入
router.get('/shop_sc/login',async (ctx)=>{
  let {shop_username,shop_password} = ctx.request.query;
  let open_id = ctx.request.header.token;
  let arr = await hq.get_zhuce(open_id,shop_username,shop_password);
  log(arr.length)
  ctx.body = JSON.stringify(arr.length);
})
//账户是否重复
router.get('/shop_sc/account',async (ctx)=>{
  let {shop_username} = ctx.request.query;
  log(shop_username)
  let arr = await hq.get_account(shop_username);
  log(arr.length)
  ctx.body = JSON.stringify(arr.length);
})
//查询状态
router.get('/shop_sc/open_id',async (ctx)=>{
  let {open_id} = ctx.request.query;
  //const open_id = ctx.request.header.token;
  let arr = await hq.get_openid(open_id);
  if(arr.length==0) ctx.body = JSON.stringify(99)
  else ctx.body = JSON.stringify(arr[0].state);
})
//更改密码
router.get('/shop_sc/password',async (ctx)=>{
  let {shop_username,old_password,shop_password} = ctx.request.query;
  let open_id = ctx.request.header.token;
  let arr = await hq.get_zhuce(open_id,shop_username,old_password);
  hq.updatepassword(arr[0].id,shop_password);
  let brr = await hq.get_zhuce(open_id,shop_username,shop_password);
  log(brr);
  ctx.body = JSON.stringify(brr);
})
//图片检查
const multiparty = require('koa2-multiparty');
router.post('/shop_sc/imgCheck', multiparty(), async (ctx) =>{
  //console.log(ctx.req.files);
  const { files } = ctx.req;
  const stream = fs.createReadStream(files.file.path)
  const accesstoken = await check.getAccessToken() 
  const checkResult = await check.imgSecCheck(accesstoken, stream)
  const jsonResult = JSON.parse(checkResult)
  //console.log(jsonResult);
  if (jsonResult.errcode !== 0) {
    ctx.body = JSON.stringify('图片违规');
  } else {
    ctx.body = JSON.stringify('dnmdzql');
  }
})
//图片上传
router.post('/shop_sc/upload', up.upload.single('file'), async (ctx, next) => {
  const filename1 = '/public/upload/'+ctx.req.file.filename
  console.log(filename1);
  ctx.body = filename1; 
});
//拉取状态
router.get('/shop_sc/select_state', async (ctx)=>{
  let {state} = ctx.request.query;
  let arr = await hq.getstate(state);
  log(arr);
  ctx.body = JSON.stringify(arr);
})
//商家拉取信息
router.get('/shop_sc/api', async (ctx)=>{
  let {pageSize,pageNum} = ctx.request.query;
  let start = pageSize * pageNum;
  let arr = await hq.select_page(start,pageSize);
  log(arr)
  let arr1 = await hq.getnum();
  log(arr1)
  let obj = new Object(); 
  obj.data = arr;
  obj.nums = arr1[0].count;
  console.log(obj);
  ctx.body = JSON.stringify(obj);
})
//审核状态
router.get('/shop_sc/state',async (ctx)=>{
  let {id,state} = ctx.request.query;
  hq.update_state(id,state);
  let arr = await hq.get_id(id);
  log(arr);
  ctx.body = JSON.stringify(arr);
})
process.on('unhandledRejection',(reason,p) => {
    console.log('Unhandled Rejection at:Promise',p,'reason:',reason);
});


app.use(router.routes())
   .use(router.allowedMethods());
//app.listen(2227);


https.createServer(options,app.callback()).listen(2122);

